import userApi from '@/api/user'

const state = {
    userList: [],
    total: 0,
    currentUser: null
}

const mutations = {
    SET_USER_LIST(state, { records, total }) {
        state.userList = records
        state.total = total
    },
    SET_CURRENT_USER(state, user) {
        state.currentUser = user
    }
}

const actions = {
    // 获取用户列表
    async getUserList({ commit }, params) {
        try {
            const response = await userApi.getPage(params)
            if (response.data.flag) {
                commit('SET_USER_LIST', response.data.data)
                return response.data
            }
            return Promise.reject(response.data.message)
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 获取用户详情
    async getUserDetail({ commit }, id) {
        try {
            const response = await userApi.getById(id)
            if (response.data.flag) {
                commit('SET_CURRENT_USER', response.data.data)
                return response.data
            }
            return Promise.reject(response.data.message)
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 添加用户
    async addUser(_, data) {
        try {
            const response = await userApi.add(data)
            return response.data
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 更新用户
    async updateUser(_, { id, data }) {
        try {
            const response = await userApi.update(id, data)
            return response.data
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 更新用户状态
    async updateUserStatus(_, { id, status }) {
        try {
            const response = await userApi.updateStatus(id, status)
            return response.data
        } catch (error) {
            return Promise.reject(error)
        }
    },

    // 删除用户
    async deleteUser(_, id) {
        try {
            const response = await userApi.delete(id)
            return response.data
        } catch (error) {
            return Promise.reject(error)
        }
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}